// 封装错误信息
import axios from 'axios'
import { Message } from 'element-ui'

//使用axios的响应拦截器
/**
 * success是服务器端的响应,响应成功进success,失败进error
 * success里的data封装的服务器响应回来的json
 */
axios.interceptors.response.use(success => {
  //如果发生业务错误
  if (success.status && success.status == 200 && success.data.status == 500) {
    //弹出错误框,显示服务器回传的错误信息
    Message.error({ message: success.data.message })
    return
  }

  if (success.data.message) {
    Message.success({ message: success.data.message })
  }

  //没有问题就返回服务器回传的值
  return success.data

}, error => {
  //判断错误类型
  if (error.response.status == 504 || error.response.status == 404) {
    Message.error({ message: '服务器错误!' })
  } else if (error.response.status == 403) {
    Message.error({ message: '你没有权限!' })
  } else if (error.response.status == 401) {
    Message.error({ message: '你没有登陆' })
  } else {
    if (error.response.data.message) {
      Message.error({ message: error.response.data.message })
    } else {
      Message.error({ message: '未知错误!' })
    }
  }
  return
})

//统一请求路径
let base = ''
//请求方法封装,默认用post,url为请求的路径,params为提交的参数,即username和password
export const postKeyValueRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    // 将JSON格式转换为键值对
    transformRequest: [function (data) {
      let ret = ''
      for (let i in data) {
        ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
      }
      // console.log(ret)
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

// 封装post方法
export const postRequest = (url, parms) => {
  return axios({
    method: 'post',
    //这里的引号要注意~~~
    url: `${base}${url}`,
    data: parms,
  })
}

// 封装put方法
export const putRequest = (url, parms) => {
  return axios({
    method: 'put',
    //这里的引号要注意~~~
    url: `${base}${url}`,
    data: parms,
  })
}

// 封装get方法
export const getRequest = (url, parms) => {
  return axios({
    method: 'get',
    //这里的引号要注意~~~
    url: `${base}${url}`,
    data: parms,
  })
}

// 封装delete方法
export const deleteRequest = (url, parms) => {
  return axios({
    method: 'delete',
    //这里的引号要注意~~~
    url: `${base}${url}`,
    data: parms,
  })
}